/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controllers;

import Controllers.exceptions.IllegalOrphanException;
import Controllers.exceptions.NonexistentEntityException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import Entities.Person;
import Entities.Appointment;
import Entities.Veterinary;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

/**
 *
 * @author Heinz Hernandez
 */
public class VeterinaryJpaController implements Serializable {

    public VeterinaryJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Veterinary veterinary) {
        if (veterinary.getAppointmentList() == null) {
            veterinary.setAppointmentList(new ArrayList<Appointment>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Person perId = veterinary.getPerId();
            if (perId != null) {
                perId = em.getReference(perId.getClass(), perId.getPerId());
                veterinary.setPerId(perId);
            }
            List<Appointment> attachedAppointmentList = new ArrayList<Appointment>();
            for (Appointment appointmentListAppointmentToAttach : veterinary.getAppointmentList()) {
                appointmentListAppointmentToAttach = em.getReference(appointmentListAppointmentToAttach.getClass(), appointmentListAppointmentToAttach.getAppoId());
                attachedAppointmentList.add(appointmentListAppointmentToAttach);
            }
            veterinary.setAppointmentList(attachedAppointmentList);
            em.persist(veterinary);
            if (perId != null) {
                perId.getVeterinaryList().add(veterinary);
                perId = em.merge(perId);
            }
            for (Appointment appointmentListAppointment : veterinary.getAppointmentList()) {
                Veterinary oldVetIdOfAppointmentListAppointment = appointmentListAppointment.getVetId();
                appointmentListAppointment.setVetId(veterinary);
                appointmentListAppointment = em.merge(appointmentListAppointment);
                if (oldVetIdOfAppointmentListAppointment != null) {
                    oldVetIdOfAppointmentListAppointment.getAppointmentList().remove(appointmentListAppointment);
                    oldVetIdOfAppointmentListAppointment = em.merge(oldVetIdOfAppointmentListAppointment);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Veterinary veterinary) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Veterinary persistentVeterinary = em.find(Veterinary.class, veterinary.getVetId());
            Person perIdOld = persistentVeterinary.getPerId();
            Person perIdNew = veterinary.getPerId();
            List<Appointment> appointmentListOld = persistentVeterinary.getAppointmentList();
            List<Appointment> appointmentListNew = veterinary.getAppointmentList();
            List<String> illegalOrphanMessages = null;
            for (Appointment appointmentListOldAppointment : appointmentListOld) {
                if (!appointmentListNew.contains(appointmentListOldAppointment)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Appointment " + appointmentListOldAppointment + " since its vetId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (perIdNew != null) {
                perIdNew = em.getReference(perIdNew.getClass(), perIdNew.getPerId());
                veterinary.setPerId(perIdNew);
            }
            List<Appointment> attachedAppointmentListNew = new ArrayList<Appointment>();
            for (Appointment appointmentListNewAppointmentToAttach : appointmentListNew) {
                appointmentListNewAppointmentToAttach = em.getReference(appointmentListNewAppointmentToAttach.getClass(), appointmentListNewAppointmentToAttach.getAppoId());
                attachedAppointmentListNew.add(appointmentListNewAppointmentToAttach);
            }
            appointmentListNew = attachedAppointmentListNew;
            veterinary.setAppointmentList(appointmentListNew);
            veterinary = em.merge(veterinary);
            if (perIdOld != null && !perIdOld.equals(perIdNew)) {
                perIdOld.getVeterinaryList().remove(veterinary);
                perIdOld = em.merge(perIdOld);
            }
            if (perIdNew != null && !perIdNew.equals(perIdOld)) {
                perIdNew.getVeterinaryList().add(veterinary);
                perIdNew = em.merge(perIdNew);
            }
            for (Appointment appointmentListNewAppointment : appointmentListNew) {
                if (!appointmentListOld.contains(appointmentListNewAppointment)) {
                    Veterinary oldVetIdOfAppointmentListNewAppointment = appointmentListNewAppointment.getVetId();
                    appointmentListNewAppointment.setVetId(veterinary);
                    appointmentListNewAppointment = em.merge(appointmentListNewAppointment);
                    if (oldVetIdOfAppointmentListNewAppointment != null && !oldVetIdOfAppointmentListNewAppointment.equals(veterinary)) {
                        oldVetIdOfAppointmentListNewAppointment.getAppointmentList().remove(appointmentListNewAppointment);
                        oldVetIdOfAppointmentListNewAppointment = em.merge(oldVetIdOfAppointmentListNewAppointment);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = veterinary.getVetId();
                if (findVeterinary(id) == null) {
                    throw new NonexistentEntityException("The veterinary with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Long id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Veterinary veterinary;
            try {
                veterinary = em.getReference(Veterinary.class, id);
                veterinary.getVetId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The veterinary with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Appointment> appointmentListOrphanCheck = veterinary.getAppointmentList();
            for (Appointment appointmentListOrphanCheckAppointment : appointmentListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Veterinary (" + veterinary + ") cannot be destroyed since the Appointment " + appointmentListOrphanCheckAppointment + " in its appointmentList field has a non-nullable vetId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Person perId = veterinary.getPerId();
            if (perId != null) {
                perId.getVeterinaryList().remove(veterinary);
                perId = em.merge(perId);
            }
            em.remove(veterinary);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Veterinary> findVeterinaryEntities() {
        return findVeterinaryEntities(true, -1, -1);
    }

    public List<Veterinary> findVeterinaryEntities(int maxResults, int firstResult) {
        return findVeterinaryEntities(false, maxResults, firstResult);
    }

    private List<Veterinary> findVeterinaryEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Veterinary.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Veterinary findVeterinary(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Veterinary.class, id);
        } finally {
            em.close();
        }
    }

    public int getVeterinaryCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Veterinary> rt = cq.from(Veterinary.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
